//
//  MZDrawerViewController.m
//  MZ_CT
//
//  Created by lanou3g on 15/12/15.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "MZDrawerViewController.h"
#import "MZDrawerView.h"
//#import <objc/objc-runtime.h>//运行时
#import "YPSongController.h"
#import "RadioDetailListModel.h"
#import "YPUser.h"
#import "UIImageView+WebCache.h"
#import "LYRadioHelper.h"
#import "LYLoginViewController.h"
#import "CollectViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
typedef enum {
    ENUM_NO_Login = 0,
    ENUM_Login,
    ENUM_SinaWeibologin,
    ENUM_TencentWeibologin
}TYPE_Login;
static BOOL isflag = NO;//是否是第一次进入程序
static MZDrawerViewController *drawer = nil;//单例
@interface MZDrawerViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,LoginViewControllerDelegate>
@property (nonatomic, strong)MZDrawerView *dv;
@property (nonatomic,strong) NSMutableArray *temp;//存放歌曲列表
@property (nonatomic,assign) NSInteger index;//当前正在播放的歌曲
@property (nonatomic,strong) YPSongController *song;
@property (nonatomic,assign) BOOL isLogin;//判断是否是登陆状态
@property (nonatomic,strong) LYLoginViewController *loginVC;
@property (nonatomic,assign) TYPE_Login loginType;
@property (nonatomic,strong) NSArray *arr;

@end

@implementation MZDrawerViewController

- (void)loadView{
    self.dv = [[MZDrawerView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = self.dv;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
    if (str == NULL || [str isEqualToString:@"nlogin"]) {
        self.dv.headView.image = [UIImage imageNamed:@"iconfont-weidenglutouxiang"];
        [self.dv.LoginOrRegister setTitle:@"登录" forState:UIControlStateNormal];
        self.loginType = ENUM_NO_Login;
    }else if([str isEqualToString:@"slogin"]){
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"userHeader"];
        self.dv.headView.image = [UIImage imageWithData:data];
        [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
        [self changeLoginAction];
        self.loginType = ENUM_SinaWeibologin;
    }else if ([str isEqualToString:@"tlogin"]){
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"userHeader"];
        self.dv.headView.image = [UIImage imageWithData:data];
        [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
        [self changeLoginAction];
        self.loginType = ENUM_TencentWeibologin;
    }else if([str isEqualToString:@"login"]){
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"userHeader"];
        self.dv.headView.image = [UIImage imageWithData:data];
        [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
        [self changeLoginAction];
        self.loginType = ENUM_Login;
    }
    _loginVC.isLogin = ^(BOOL flag){
        _isLogin = flag;
    };
    _song.block = ^(NSMutableArray *arr,NSInteger index){
        isflag = YES;
        _temp = arr;
        _index = index;
    };
    if (isflag) {
        [self setBottomView];
        [self.dv.playOrPause setImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _arr =@[@"首页", @"电台", @"阅读", @"社区", @"良品", @"设置"];
    self.view.backgroundColor = [UIColor lightGrayColor];
    [self.dv.optionalList registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.dv.optionalList.dataSource = self;
    self.dv.optionalList.delegate = self;
    self.dv.optionalList.scrollEnabled = NO;
    self.dv.optionalList.separatorStyle = UITableViewCellSeparatorStyleNone;
    _loginVC = [[LYLoginViewController alloc]init];
    _loginVC.delegate = self;
    _song = [YPSongController shareSongController];
    [self setupView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUI) name:@"HomePageUI" object:nil];
}

- (void)changeLoginAction{
    [self.dv.LoginOrRegister removeTarget:self action:@selector(LoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.dv.LoginOrRegister addTarget:self action:@selector(changeUser) forControlEvents:UIControlEventTouchUpInside];
}
- (void)loginSuccessWithName:(NSString *)name andImage:(UIImage*)image{
    self.loginType = ENUM_Login;
    self.dv.headView.image = image;
    [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
    [self changeLoginAction];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"userName"];//用户名称
    [[NSUserDefaults standardUserDefaults] setObject:[self transformToData:image] forKey:@"userHeader"];//用户登陆状态
    [[NSUserDefaults standardUserDefaults] setObject:@"login" forKey:@"login"];
}

- (void)SinaWeibologinSuccessWith:(NSString *)name andImage:(NSString *)image{
    self.loginType = ENUM_SinaWeibologin;
    [self.dv.headView sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:@"16"]];
    [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
    [self changeLoginAction];
    [self getImageWith:image success:^(NSData *data) {
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"userHeader"];
    } faile:^(NSError *err) {
        
    }];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"userName"];//用户名称
    [[NSUserDefaults standardUserDefaults] setObject:@"slogin" forKey:@"login"];
}
- (void)TencentWeibologinSuccessWith:(NSString *)name andImage:(NSString*)image{
    self.loginType = ENUM_TencentWeibologin;
    [self.dv.headView sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:@"16"]];
    [self.dv.LoginOrRegister setTitle:name forState:UIControlStateNormal];
    [self changeLoginAction];
    [self getImageWith:image success:^(NSData *data) {
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"userHeader"];
    } faile:^(NSError *err) {
        
    }];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"userName"];//用户名称
    //用户登陆状态
    [[NSUserDefaults standardUserDefaults] setObject:@"tlogin" forKey:@"login"];
}
//图片加载的方法
-(void)getImageWith:(NSString*)url success:(void (^)(NSData*))success faile:(void (^)(NSError *))faile{
    //开辟一个新的线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        if (data == nil) {
            NSError *err = [NSError errorWithDomain:@"error" code:1 userInfo:nil];
            faile(err);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            success(data);
        });
    });
}

- (void)changeUser{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要更换用户" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        switch (self.loginType) {
            case ENUM_Login:
                [AVUser logOut];
                break;
             case ENUM_TencentWeibologin:
                [ShareSDK cancelAuthorize:SSDKPlatformTypeTencentWeibo];
                break;
                case ENUM_SinaWeibologin:
                [ShareSDK cancelAuthorize:SSDKPlatformTypeSinaWeibo];
                break;
            default:
                break;
        }
        [self.dv.LoginOrRegister removeTarget:self action:@selector(changeUser) forControlEvents:UIControlEventTouchUpInside];
        [self.dv.LoginOrRegister addTarget:self action:@selector(LoginAction:) forControlEvents:UIControlEventTouchUpInside];

        [[NSUserDefaults standardUserDefaults] setObject:@"nlogin" forKey:@"login"];
        [self presentViewController:_loginVC animated:YES completion:nil];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)setupView{
    self.dv.headView.userInteractionEnabled = YES;//打开用户交互
    //添加手势，更换头像
    [self.dv.LoginOrRegister addTarget:self action:@selector(LoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.dv.collection setImage:[UIImage imageNamed:@"iconfont-iconfontshoucang"] forState:UIControlStateNormal];
    [self.dv.collection addTarget:self action:@selector(pushAction) forControlEvents:UIControlEventTouchUpInside];
    [self.dv.skinnable setImage:[UIImage imageNamed:@"iconfont-jiemianzhuti"] forState:UIControlStateNormal];
    [self.dv.skinnable addTarget:self action:@selector(downLoadAction:) forControlEvents:UIControlEventTouchUpInside];
    self.dv.bottomView.image = [UIImage imageNamed:@"bottom"];
    self.dv.radioView.image = [UIImage imageNamed:@"DrawerVCMusic"];
    self.dv.radioTheme.text = @"XXXX";
    self.dv.radioSummary.text = @"XXXX";
    UITapGestureRecognizer *radioTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(radioTapAction:)];
    [self.dv.radioView addGestureRecognizer:radioTap];
    [self.dv.playOrPause setImage:[UIImage imageNamed:@"music_play_button_32px_1182975_easyicon.net"] forState:UIControlStateNormal];
    [self.dv.playOrPause addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)pushAction{
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"login"];
    if (str == nil || [str isEqualToString:@"nlogin"]) {
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault handler:nil];
        [controller addAction:action];
        [self presentViewController:controller animated:YES completion:nil];
    }else{
        CollectViewController *collect = [[CollectViewController alloc]init];
        [self presentViewController:[[UINavigationController alloc]initWithRootViewController:collect] animated:YES completion:nil];
    }
}

- (void)downLoadAction:(UIButton*)sender{
    self.view.backgroundColor = [UIColor colorWithRed:arc4random()% 255 / 256.0 green:arc4random()% 255 / 256.0 blue:arc4random()% 255 / 256.0 alpha:arc4random()% 255 / 256.0];
}

- (void)setBottomView{
    RadioDetailListModel *model = self.temp[self.index];
    self.dv.radioTheme.text = model.title;//电台的名字
    self.dv.radioSummary.text = model.authorinfo.uname;//主播的名称
    [self.dv.radioView sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:[UIImage imageNamed:@"1"]];
}

- (void)updateUI{
    self.index++;
    if (_index == self.temp.count) {
        _index = 0;
    }
    [self setBottomView];
}

- (NSMutableArray *)temp{
    if (_temp == nil) {
        _temp = [NSMutableArray array];
    }
    return _temp;
}

- (void)radioTapAction:(UITapGestureRecognizer*)sender{
    _song.index = self.index;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:_song];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)playAction:(UIButton*)sender{
    sender.selected = !sender.selected;
    if (isflag) {
        if (sender.selected) {//暂停状态
            [self.dv.playOrPause setImage:[UIImage imageNamed:@"music_play_button_32px_1182975_easyicon.net"] forState:UIControlStateNormal];
        }else{//播放状态
            [self.dv.playOrPause setImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateButton" object:nil];
    }
}

- (void)LoginAction:(UIButton*)sender{
    [self presentViewController:_loginVC animated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *imageArr = @[@"drawer_01", @"drawer_02", @"drawer_03", @"drawer_04", @"drawer_05", @"drawer_06"].mutableCopy;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:imageArr[indexPath.row]];
    cell.textLabel.text = self.arr[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50 * ([UIScreen mainScreen].bounds.size.height / 667.0);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.delegate getIndex:indexPath.row fromVC:self str:_arr[indexPath.row]];
}

+ (instancetype)shareDrawerVC{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        drawer = [[MZDrawerViewController alloc]init];
    });
    return drawer;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//照片转换成NSData类型
-(NSData*)transformToData:(UIImage*)t_image{
    NSData *imageData = UIImagePNGRepresentation(t_image);
    if (imageData == nil) {
        imageData = UIImageJPEGRepresentation(t_image, 1);
    } else {
        imageData = UIImagePNGRepresentation(t_image);
    }
    return imageData;
}

@end
